package com.common.aop;

import java.lang.reflect.Method;

import org.aspectj.lang.JoinPoint;

import com.common.annotation.DataSource;
import com.common.datasource.DataSourceHolder;


public class DataSourceAspect {

	/**
	 * 切换数据源
	 * @param jp
	 */
	public void changeDateSource(JoinPoint jp) {
		try {
			String methodName = jp.getSignature().getName();
			Class<?> targetClass = Class.forName(jp.getTarget().getClass().getName());
			for (Method method : targetClass.getMethods()) {
				if (methodName.equals(method.getName())) {
					Class<?>[] args = method.getParameterTypes();
					if (args.length == jp.getArgs().length) {
						DataSource ds = method.getAnnotation(DataSource.class);
						DataSourceHolder.setCustomeType(ds.value().getName());
					}
				}
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 重置数据源
	 * @param jp
	 */
	public void restoreDataSource() {
		try {
			DataSourceHolder.remove();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}